#include "ulib.h"

static void
process_container(process_func_t func, void *data)
{
	 func(data);
	 
	 sc_kprintf("Process %d ends.\n", cur_pid());
	 while (1) ;
	 /* TODO user resource clean up */
	 /* Then call the system to free the kernel resource */
	 // sc_proc_exit();
}

int
process_create(process_func_t func, void *data, int stack_size)
{
	 /* Find the address for user stack */
	 char *stack_top = (char *)va_alloc(stack_size), *cur;
	 if (stack_top == 0) return -E_NO_MEM;
	 char *stack = PAGE_ALIGN(stack_top + stack_size - 1) + PAGE_SIZE;

	 for (cur = stack_top; cur < stack; cur += PAGE_SIZE)
		  sc_alloc_temp_4K((void *)cur);

	 stack -= sizeof(void *);
	 *(void **)stack = data;
	 stack -= sizeof(process_func_t);
	 *(process_func_t *)stack = func;
	 /* The fake return address */
	 stack -= sizeof(void *);
	 *(void **)stack = NULL;
	 
	 int err = sc_fork_proc(process_container, (uint32_t)stack);
	 if (err < 0)
	 {
		  /* TODO clean up */
	 }
	 return err;
}
